﻿using PostSharp.Aspects;
using Shared.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Services.Aspects
{
    [Serializable]
    public class CacheAttribute : CacheActionAttribute
    {
        public bool NoExpiration { get; set; }

        /// <summary>
        /// In Seconds
        /// </summary>
        public int Duration { get; set; }

        public override void OnInvoke(MethodInterceptionArgs args)
        {
            TimeSpan? timeSpan = null;
            if (Duration > 0)
                timeSpan = TimeSpan.FromSeconds(Duration);
            if (NoExpiration)
                timeSpan = TimeSpan.FromDays(30);

            string key = GetCacheKey(args);
            args.ReturnValue = cacheStorage.Get<object>(key, () =>
            {
                args.Proceed();
                return args.ReturnValue;
            }, timeSpan);
        }
    }
}
